package thread.atomic;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * ABA问题
 *
 * @author liweimin
 * @date 2021/4/29 17:51
 * @since
 */
public class AtomicReferenceABATest {
    //    private static AtomicReference<String> atomicReference = new AtomicReference<>("abc");
    private static AtomicStampedReference<String> atomicReference = new AtomicStampedReference("abc", 0);//初始版本号

    public static void main(String[] args) {
        int stamp = atomicReference.getStamp();
        new Thread(() -> {
//            atomicReference.compareAndSet("abc", "def");
            atomicReference.compareAndSet("abc", "def", atomicReference.getStamp(), atomicReference.getStamp() + 1);
            System.out.println(Thread.currentThread().getName() + "---" + atomicReference.getReference());
//            System.out.println(Thread.currentThread().getName() + "---" + atomicReference.get());
//            atomicReference.compareAndSet("def", "abc");
            atomicReference.compareAndSet("def", "abc", atomicReference.getStamp(), atomicReference.getStamp() + 1);
        }).start();


        new Thread(() -> {

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(atomicReference.compareAndSet("abc", "igh", stamp, stamp + 1) + "修改后的值为：" + atomicReference.getReference());
//            System.out.println(atomicReference.compareAndSet("abc", "igh") + "修改后的值为：" + atomicReference.get());
        }).start();


    }
}

